<template>
  <basic-container>
    <avue-crud
      :option="option"
      :data="data"
      :table-loading="loading"
      :page.sync="page"
      ref='crud'
      @row-del="rowDel"
      v-model="form"
      :permission="permissionList"
      @row-update="rowUpdate"
      @row-save="rowSave"
      :before-open="beforeOpen"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @row-click="handleRowClick"
      @refresh-change="refreshChange"
      @on-load="onLoad">
      <template slot="menuLeft">
        <table-right :crud='$refs.crud' :data='data'  :refreshChange='refreshChange'>
          <div class="top-bar__item iconDiv" @click="handleDelete" v-if="permission.materialgroup_delete" >
            <i class="el-icon-delete" style="font-size:20px;"></i>
            <span style="font-size: 12px;color:#1e1e1e;">&nbsp;批量删除</span>
          </div>
        </table-right>
      </template>
      <template slot-scope="{row}" slot="status">
        {{row.status==1?'在用':'停产'}}
      </template>
      <template slot-scope="{scope,row}" slot="menuForm">
        <el-button icon="el-icon-circle-plus" v-if="type=='add'" v-loading="goon" size="mini" plain type="primary" @click.stop="saveAndGoon()">保存并继续</el-button>
      </template>
      <template slot-scope="{row}" slot="menu">
        <el-tooltip class="item" effect="dark" content="查看" placement="bottom">
          <el-button icon="el-icon-view" size="small" type="text" @click.stop="$refs.crud.rowView(row,row.$index)" v-if="permission.materialgroup_view"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
          <el-button icon="el-icon-edit" size="small" type="text" @click.stop="$refs.crud.rowEdit(row,row.$index)" v-if="permission.materialgroup_edit"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
          <el-button icon="el-icon-delete" size="small" type="text" @click.stop="rowDel(row)" v-if="permission.materialgroup_delete"></el-button>
        </el-tooltip>
      </template>
    </avue-crud>
    <el-drawer :wrapperClosable='false' :title="title" :visible.sync="showDialog" append-to-body>
      <material-group-main @reload="reload" @closeAfter="closeAfter" :openType="openType" :row="clickRow" :type="openType" @close="showDialog=false" v-if="showDialog" />
    </el-drawer>
  </basic-container>
</template>

<script>
import {
  getMaterialgroupPage,
  addMaterialgroup,
  removeMaterialgroup,
  updateMaterialgroup,
  getMaterialgroup,
} from '@/api/project/productData/baseData';
import { mapGetters } from 'vuex';
import {init, offFunction} from '@/mixins/init';
import { twoLetterReg } from '@/util/zhengze';
import { searchSpan, culomnSpan } from '@/api/span';
import MaterialGroupMain from "@/views/publicmaterial/materialGroupMain";
export default {
  components: {MaterialGroupMain},
  mixins: [init,offFunction],
  data() {
    return {
      showDialog:false,
      option: {
        size: '',
        // height: 'auto',
        dialogHeight: '100%',
        dialogWidth: '700',
        calcHeight: 80,
        tip: false,
        border: false,
        index: true,
        indexLabel: '序号',
        selection: true,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        searchShow:false,
        emptyBtnText:'重 置',
        emptyBtnIcon: 'el-icon-refresh',
        menu:false,
        highlightCurrentRow:true,
        addBtn: false,
        menuWidth: 100,
        searchLabelWidth: 100,
        searchMenuSpan: searchSpan(3),
        dialogClickModal: false,
        column: [
          {
            label: '零件组编码',
            prop: 'materialGroupNo',
            span: 24,
            search: true,
            searchSpan: culomnSpan(),
            minWidth: 150,
            labelWidth: '100',
            maxlength: 2,
            rules: [
              {
                required: true,
                message: '请输入零件组编码',
                trigger: 'blur',
              },
              {
                pattern: twoLetterReg,
                message: '零件编码由大写字母或数字组成，共两位',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '零件组名称',
            prop: 'materialGroupName',
            search: true,
            searchSpan: culomnSpan(),
            span: 24,
            minWidth: 150,
            labelWidth: '100',
            maxlength: 40,
            rules: [
              {
                required: true,
                message: '请输入零件组名称',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '零件类型',
            prop: 'materialFlagType',
            span: 24,
            minWidth: 150,
            labelWidth: '100',
            type: 'cascader',
            search: true,
            searchSpan: culomnSpan(),
            dicUrl: '/api/materialgroup/getTree?code=materials',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            rules: [
              {
                required: true,
                message: '请选择零件类型',
                trigger: 'blur',
              },
            ],
          },
          // {
          //   label: '零件组分类',
          //   prop: 'materialGroupType',
          //   span: 24,
          //   minWidth: 150,
          //   labelWidth: '100',
          //   type: 'select',
          //   dicUrl: '/api/blade-system/dict-biz/dictionary?code=materialGroupType',
          //   props: {
          //     label: 'dictValue',
          //     value: 'dictKey',
          //   },
          //   rules: [
          //     {
          //       required: true,
          //       message: '请选择零件组分类',
          //       trigger: 'blur',
          //     },
          //   ],
          // },
        ],
      },
      data: [],
    };
  },
  watch: {},
  computed: {
    ...mapGetters(['userInfo', 'permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.materialgroup_add, false),
        viewBtn: this.vaildData(this.permission.materialgroup_view, false),
        delBtn: this.vaildData(this.permission.materialgroup_delete, false),
        editBtn: this.vaildData(this.permission.materialgroup_edit, false),
      };
    },
  },
  mounted() {
    setTimeout(() => {
      this.$EventBus.$emit('publicBtn', {add:this.permission.materialgroup_add})
    }, 200)
    this.$EventBus.$on("publicBtnClick", (params) => {
      if (params == "add") {
        this.addFn()
      }else if (params == "edit") {
        this.rowEdit (this.clickRow)
      }else if (params == "del") {
        this.rowDel(this.clickRow)
      } else if (params == 'view') {
        this.rowView(this.clickRow)
      }
    });
  },
  // created() {
  //   this.onLoad(this.page);
  // },
  methods: {
    rowSave(row, done, loading) {
      row.materialFlag = row.materialFlagType[0];
      row.materialType = row.materialFlagType[1];
      addMaterialgroup(row).then(
        () => {
          if (this.goon) {
            loading();
            for (let key in this.$refs.crud.value) {
              this.$refs.crud.value[key] = null;
            }
            this.goon = false;
            this.onLoad(this.page);
          } else {
            this.onLoad(this.page);
            done();
          }
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        },
        (error) => {
          this.goon = false;
          window.console.log(error);
          loading();
        }
      );
    },
    // rowSave(row, done, loading) {
    //   row.materialFlag = row.materialFlagType[0];
    //   row.materialType = row.materialFlagType[1];
    //   addMaterialgroup(row).then(
    //     () => {
    //       this.onLoad(this.page);
    //       this.$message({
    //         type: 'success',
    //         message: '操作成功!',
    //       });
    //       done();
    //     },
    //     (error) => {
    //       window.console.log(error);
    //       loading();
    //     }
    //   );
    // },
    rowUpdate(row, index, done, loading) {
      row.materialFlag = row.materialFlagType[0];
      row.materialType = row.materialFlagType[1];
      updateMaterialgroup(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm(this.deleteFnMessageText, '提示', {
        confirmButtonText: this.confirmButtonText,
        cancelButtonText: this.cancelButtonText,
        type: 'warning',
      })
        .then(() => {
          return removeMaterialgroup(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm(this.deleteFnMessageText, '提示', {
        confirmButtonText: this.confirmButtonText,
        cancelButtonText: this.cancelButtonText,
        type: 'warning',
      })
        .then(() => {
          return removeMaterialgroup(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },

    handleRowClick (row) {
      if (row.id == this.clickRow.id) {
        this.clickRow = {}
        this.$refs.crud.setCurrentRow()
        this.$EventBus.$emit('publicBtn', {add:this.permission.materialgroup_add});
      } else {
        this.clickRow = row;
        this.$EventBus.$emit('publicBtn', {
          add:this.permission.materialgroup_add,
          del:this.permission.materialgroup_delete,
          view:this.permission.materialgroup_view,
          edit:this.permission.materialgroup_edit,
        });
      }
    },

    beforeOpen(done, type) {
      this.type = type;
      if (['edit', 'view'].includes(type)) {
        getMaterialgroup(this.form.id).then((res) => {
          let data = res.data.data;
          data.materialFlagType = [data.materialFlag, data.materialType];
          this.form = data;
          this.form.status = data.status + '';
        });
      } else {
        this.form.status = '1';
      }
      done();
    },
    onLoad(page, params = {}) {
      this.$EventBus.$emit('publicBtn', {add:this.permission.materialgroup_add})
      this.closeTooltip();
      this.loading = true;
      let { materialFlagType } = params;
      if (materialFlagType) {
        this.query.materialFlag = materialFlagType[0];
        this.query.materialType = materialFlagType[1];
        delete this.query.materialFlagType;
      }
      getMaterialgroupPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records.map((item) => {
          item.materialFlagType = [item.materialFlag, item.materialType];
          return item;
        });
        this.loading = false;
        this.selectionClear();
        this.$nextTick(() => {
          this.$refs.crud.setCurrentRow()
        })
      });
    },
    reload(){
      this.showDialog = false;
      this.onLoad(this.page);
    },
    closeAfter(){
      this.onLoad(this.page);
    },
    addFn(){
      this.title = '新增零件组';
      this.openType = 'add';
      this.showDialog = true;
    },
    rowEdit(){
      this.title = '编辑零件组';
      this.openType = 'edit';
      this.showDialog = true;
    },
    rowView(){
      this.title = '查看零件组';
      this.openType = 'view';
      this.showDialog = true;
    },
  },
};
</script>

<style>
.box {
  height: 800px;
}

.el-scrollbar {
  height: 100%;
}

.box .el-scrollbar__wrap {
  overflow: scroll;
}
</style>
